package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ijpay.core.kit.WxPayKit;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.BusinessException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.SysUserCommonConfig;
import org.dromara.system.domain.SysUserGetMachineRecords;
import org.dromara.system.domain.SysUserInviteConfig;
import org.dromara.system.domain.bo.GetMachineBo;
import org.dromara.system.domain.bo.InitGetMachineBo;
import org.dromara.system.domain.bo.SysUserGetMachineRecordsBo;
import org.dromara.system.domain.bo.SysUserPurseBo;
import org.dromara.system.domain.vo.SysUserGetMachineRecordsVo;
import org.dromara.system.enums.GetMachineEnum;
import org.dromara.system.enums.MachineConstant;
import org.dromara.system.enums.PayTypeEnum;
import org.dromara.system.enums.SysUserFreezePointsRecordsEnum;
import org.dromara.system.mapper.SysUserGetMachineRecordsMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.ISysUserCommonConfigService;
import org.dromara.system.service.ISysUserFreezePointsRecordsService;
import org.dromara.system.service.ISysUserGetMachineRecordsService;
import org.dromara.system.service.ISysUserInviteConfigService;
import org.dromara.system.service.impl.pay.AbstractPayService;
import org.dromara.system.service.impl.permission.PermissionBaseService;
import org.dromara.system.util.JsonUtil;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 领取机具记录Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-24
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysUserGetMachineRecordsServiceImpl extends ServiceImpl<SysUserGetMachineRecordsMapper, SysUserGetMachineRecords> implements ISysUserGetMachineRecordsService {

    public static final String PREFIX = "TDL";
    private final SysUserMapper sysUserMapper;
    private final ISysUserCommonConfigService commonConfigService;
    private final PermissionBaseService permissionBaseService;
    private final ISysUserInviteConfigService sysUserInviteConfigService;
    private final ISysUserFreezePointsRecordsService sysUserFreezePointsRecordsService;
    @Resource
    private Map<String, AbstractPayService> abstractPayServiceMap;

    public static synchronized String getOrderNo(int digit) {
        StringBuilder resultBuffer = new StringBuilder();
        resultBuffer.append(PREFIX)
            .append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        Random random = new Random();
        for (int i = 0; i < digit; i++) {
            resultBuffer.append(random.nextInt(10));
        }
        return resultBuffer.toString();
    }

    /**
     * 查询领取机具记录
     *
     * @param id 主键
     * @return 领取机具记录
     */
    @Override
    public SysUserGetMachineRecordsVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询领取机具记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 领取机具记录分页列表
     */
    @Override
    public TableDataInfo<SysUserGetMachineRecordsVo> queryPageList(SysUserGetMachineRecordsBo bo, PageQuery pageQuery) {
        permissionBaseService.assignPermission(bo);
        IPage<SysUserGetMachineRecordsVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<SysUserGetMachineRecordsVo> list = baseMapper.findAll(page, bo);
        return TableDataInfo.build(list);
    }

    @Override
    public TableDataInfo<SysUserGetMachineRecordsVo> listReception(SysUserGetMachineRecordsBo bo, PageQuery pageQuery) {
        permissionBaseService.aloneAssignPermission(bo);
        IPage<SysUserGetMachineRecordsVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        IPage<SysUserGetMachineRecordsVo> list = baseMapper.findAll(page, bo);
        return TableDataInfo.build(list);
    }

    /**
     * 查询符合条件的领取机具记录列表
     *
     * @param bo 查询条件
     * @return 领取机具记录列表
     */
    @Override
    public List<SysUserGetMachineRecordsVo> queryList(SysUserGetMachineRecordsBo bo) {
        LambdaQueryWrapper<SysUserGetMachineRecords> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysUserGetMachineRecords> buildQueryWrapper(SysUserGetMachineRecordsBo bo) {
        LambdaQueryWrapper<SysUserGetMachineRecords> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SysUserGetMachineRecords::getId);
        lqw.eq(bo.getUserId() != null, SysUserGetMachineRecords::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getNo()), SysUserGetMachineRecords::getNo, bo.getNo());
        lqw.eq(bo.getGetMachinePrice() != null, SysUserGetMachineRecords::getGetMachinePrice, bo.getGetMachinePrice());
        lqw.eq(bo.getNumber() != null, SysUserGetMachineRecords::getNumber, bo.getNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getUserAddress()), SysUserGetMachineRecords::getUserAddress, bo.getUserAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getShipData()), SysUserGetMachineRecords::getShipData, bo.getShipData());
        lqw.eq(bo.getStatus() != null, SysUserGetMachineRecords::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增领取机具记录
     *
     * @param bo 领取机具记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SysUserGetMachineRecordsBo bo) {
        SysUserGetMachineRecords add = MapstructUtils.convert(bo, SysUserGetMachineRecords.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改领取机具记录
     *
     * @param bo 领取机具记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SysUserGetMachineRecordsBo bo) {
        SysUserGetMachineRecords update = MapstructUtils.convert(bo, SysUserGetMachineRecords.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysUserGetMachineRecords entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除领取机具记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public BigDecimal queryGetMachinePrice() {
        SysUser sysUser = sysUserMapper.selectById(LoginHelper.getUserId());
        Long oneId = sysUser.getOneId();
        SysUserCommonConfig sysUserCommonConfig = commonConfigService.lambdaQuery().eq(SysUserCommonConfig::getUserId, oneId).one();
        return Convert.toBigDecimal(sysUserCommonConfig.getGetMachinePrice(), BigDecimal.ZERO);
    }

    @Override
    public String getMachine(GetMachineBo getMachineBo) {
        SysUser sysUser = sysUserMapper.selectById(LoginHelper.getUserId());
        SysUserCommonConfig sysUserCommonConfig = commonConfigService.lambdaQuery().eq(SysUserCommonConfig::getUserId, sysUser.getOneId()).one();
        BusinessException.isNull(sysUserCommonConfig, "未查询到用户的配置信息！");
        BigDecimal getMachinePrice = sysUserCommonConfig.getGetMachinePrice();
        BusinessException.isTrue(NumberUtil.isLessOrEqual(getMachinePrice, BigDecimal.ZERO), "未查询到用户设置的领取机具价格！");
        AbstractPayService abstractCashBack = abstractPayServiceMap.get(
            PayTypeEnum.findOne(getMachineBo.getPayType()).getServiceName());
        SysUserGetMachineRecordsBo memberRecordsBo = SysUserGetMachineRecordsBo.builder()
            .no(getOrderNo(10))
            .userId(LoginHelper.getUserId())
            .getMachinePrice(getMachinePrice)
            .number(MachineConstant.NUMBER.ONE)
            .status(GetMachineEnum.UNPAID.getCode())
            .userAddress(getMachineBo.getUserAddress())
            .build();
        InitGetMachineBo initPayMemberBo = InitGetMachineBo.builder()
            .sysUserGetMachineRecordsBo(memberRecordsBo)
            .sysUser(sysUser)
            .getMachinePrice(getMachinePrice)
            .wechatCode(getMachineBo.getWechatCode())
            .openId(getMachineBo.getOpenId())
            .build();
        insertByBo(memberRecordsBo);
        return abstractCashBack.initPayGetMachine(initPayMemberBo);
    }


    @Override
    public String wxPayCallback(HttpServletRequest request, HttpServletResponse response) {
        try {
            String xmlMsg = readData(request);
            log.info("开通vip回调返回{}", JsonUtil.toJSONString(xmlMsg));
            Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);
            String returnCode = params.get("return_code");
            if (WxPayKit.codeIsOk(returnCode) && WxPayKit.codeIsOk(returnCode)) {
                Long recordsId = Convert.toLong(params.get("attach"));
                SysUserGetMachineRecords sysUserGetMachineRecords = lambdaQuery().eq(SysUserGetMachineRecords::getId, recordsId).one();
                dealGetMachineWork(sysUserGetMachineRecords);
                Map<String, String> xml = new HashMap<String, String>(2);
                xml.put("return_code", "SUCCESS");
                xml.put("return_msg", "OK");
                return WxPayKit.toXml(xml);
            }
        } catch (Exception e) {
            log.info("微信支付回调失败：{}", e.toString());
        }
        return null;
    }

    private void dealGetMachineWork(SysUserGetMachineRecords sysUserGetMachineRecords) {
        //将订单状态变为已支付状态
        lambdaUpdate().set(SysUserGetMachineRecords::getStatus, GetMachineEnum.PENDING_SHIPMENT.getCode())
            .eq(SysUserGetMachineRecords::getId, sysUserGetMachineRecords.getId())
            .update();
        //处理邀请好友领机具返现
        SysUser sysUser = sysUserMapper.selectById(sysUserGetMachineRecords.getUserId());
        //查询pid为这个的人邀请了几个好友领取机具
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getPId, sysUser.getPId());
        List<SysUser> sysUsers = sysUserMapper.selectList(wrapper);
        List<Long> list = sysUsers.stream().map(SysUser::getUserId).toList();
        Integer userGetMachine = super.baseMapper.findUserGetMachine(list);
        //查询oneID的配置
        SysUserInviteConfig sysUserInviteConfig = sysUserInviteConfigService.lambdaQuery()
            .eq(SysUserInviteConfig::getUserId, sysUser.getOneId())
            .eq(SysUserInviteConfig::getInviteNum, userGetMachine)
            .one();
        if (ObjectUtil.isNotNull(sysUserInviteConfig)) {
            SysUserPurseBo sysUserPurseBoFrozen = SysUserPurseBo.builder()
                .userId(sysUser.getPId())
                .type(SysUserFreezePointsRecordsEnum.INVITE_GET_MACHINE_DECREASE_POINTS.getCode())
                .freezePoints(sysUserInviteConfig.getInvitePoints())
                .build();
            sysUserFreezePointsRecordsService.updateUserFreezePoints(CollUtil.newArrayList(sysUserPurseBoFrozen));
        }
        LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysUser::getUserId, sysUser.getUserId());
        updateWrapper.set(SysUser::getGetMachineTag, MachineConstant.NUMBER.ONE);
        sysUserMapper.update(updateWrapper);
    }


    public String readData(HttpServletRequest request) {
        BufferedReader br = null;
        try {
            StringBuilder result = new StringBuilder();
            br = request.getReader();
            for (String line; (line = br.readLine()) != null; ) {
                if (result.length() > 0) {
                    result.append("\n");
                }
                result.append(line);
            }
            return result.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
